package com.itany.shop.service.impl;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserNotLoginException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.OrderService;
import com.itany.shop.util.ParameterUtil;
import com.itany.shop.vo.Cart;

import java.util.List;

/**
 * @author 石小俊
 * @date 2023年10月30日 9:09
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao = (ItemDao) ObjectFactory.getObject("itemDao");

    @Override
    public String createOrder(Cart cart, User user) throws UserNotLoginException {
        if(null == cart || null == user){
            throw new UserNotLoginException("用户未登录,请先登录");
        }

        // 1.保存订单
        Order order = new Order();
        order.setUser(user);
        order.setPrice(cart.getPrice());
        order.setNo(ParameterUtil.createNo2());

        Long id = orderDao.insertReturnPrimaryKey(order);
        // 将返回的主键赋值给当前对象
        order.setId(id);

        // 2.保存明细
        // 取出需要保存的所有明细信息
        List<Item> items = cart.getItems();
        for(Item item : items){
            // 遍历这些明细,每遍历一条数据,保存一条记录
            // 由于购物车中的明细没有与之对应的订单信息
            // 将当前明细都放在当前保存的订单中
            item.setOrder(order);
            itemDao.insertItem(item);
        }
        return order.getNo();
    }

    @Override
    public List<Order> findMyOrders(User user) throws UserNotLoginException {
        if(null == user){
            throw new UserNotLoginException("用户未登录,请先登录");
        }
        List<Order> orders = orderDao.selectByUserId(user.getId());
        return orders;
    }

    @Override
    public Order findDetail(String id) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(id)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        Order order = orderDao.selectDetailById(Integer.parseInt(id));
        return order;
    }
}
